<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator;
use Session;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Models\ArticleModel;
use App\Http\Models\CategoryModel;
class ArticleController extends Controller
{



    public function index()
    {
        $data['data'] = ArticleModel::paginate(10);
        $data['type']=3 ;
        return view('article.index',compact('data'));
    }


    public function add(Request $request){

        if ($request->isMethod('get')){

            return view('article.add');
        }else{
            $data = $request->except(['_token','uploadfile']);
            $validator = Validator::make($data, [
                'title'     => 'required|string',
                'content'     => 'required|string',
            ]);
            if ($validator->fails()) {
                return redirect('/admin/article/add')
                    ->withErrors($validator)
                    ->withInput($data);
            }
            ArticleModel::create($data);
            $data['data'] = ArticleModel::paginate(10);
            $data['type']=3 ;
            return redirect('/admin/article/articlelist');
        }
        //dd($request->all());
    }

    public  function edit(Request $request,$id){

        if ($request->isMethod('get')){

            $data = ArticleModel::where(['id' => $id])->first()->toArray();

            return view('article.edit', compact('data'));
        }else{
            $data = $request->except(['_token','uploadfile']);
            $validator = Validator::make($data, [
                'title'     => 'required|string',
                'content'     => 'required|string',
            ]);
            if ($validator->fails()) {
                return redirect('/admin/article/edit')
                    ->withErrors($validator)
                    ->withInput($data);
            }
             ArticleModel::where(['id'=>$id])->update($data);

             return redirect('/admin/article/articlelist');
        }

    }

    public function del_article(Request $request )
    {

        $id = $request->input('id');
        $res = ArticleModel::where(['id'=>$id])->first();
        if(!empty($res)) {
            ArticleModel::where(['id'=>$id])->delete();
            return response()->json(['status' => 200, 'msg' =>'删除成功']);
        }
        return response()->json(['status' => 500, 'msg' =>'删除失败']);
    }

    public  function utf8_str_to_unicode($utf8_str) {
            $unicode = 0;
            $unicode = (ord($utf8_str[0]) & 0x1F) << 12;
            $unicode |= (ord($utf8_str[1]) & 0x3F) << 6;
            $unicode |= (ord($utf8_str[2]) & 0x3F);
            return dechex($unicode);
        }




}
